<!--test.vue-->
<template>
	<div>
		<div v-if="!play" class="sxc-text" v-html="text" :contenteditable="!isChange" @input="changeText" @dblclick="dbfunction($event)" @blur="blurFunc"></div>
		<template v-else>
			<div class="sxc-text" v-if="textDisType===1" v-html="text"></div>
			<sxc-scroll-text v-else :dataList="dataList" :scrollType="scrollType" />
		</template>
	</div>
</template>

<script>
	export default {
		name: 'sxc-text',
		props: {
			value: {
				type: String,
				default: '双击编辑'
			},
			textDisType: {
				type: Number,
				default: 1
			},
			play: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				text: this.value,
				isChange: true
			}
		},
		mounted() {},
		computed: {
			dataList() {
				return [{
					text: this.value
				}]
			},
			scrollType() {
				const {
					textDisType
				} = this
				let res;
				switch(textDisType) {
					case 2:
						res = 'scroll-up'
						break;
					case 3:
						res = 'scroll-up-linear'
						break;
					case 4:
						res = 'scroll-left'
						break;
					case 5:
						res = 'scroll-left-linear'
						break;
					default:
						res = 'scroll-up'
						break;
				}
				return res;
			}
		},
		watch: {
			value(n1, nv2) {
				if(this.isChange) {
					this.text = n1
				}
			}
		},
		methods: {
			changeText() {
				this.$emit('update:value', this.$el.innerHTML)
			},
			blurFunc() {
				this.isChange = true
				this.$emit('blurFunc')
			},
			dbfunction(e) {
				let _this = this;
				let obj = e.target;
				setTimeout(() => {
					if(window.getSelection) { //ie11 10 9 ff safari
						obj.focus(); //解决ff不获取焦点无法定位问题
						let range = window.getSelection(); //创建range
						range.selectAllChildren(obj); //range 选择obj下所有子内容
						range.collapseToEnd(); //光标移至最后
					} else if(document.selection) { //ie10 9 8 7 6 5
						let range = document.selection.createRange(); //创建选择对象
						range.moveToElementText(obj); //range定位到obj
						range.collapse(false); //光标移至最后
						range.select();
					}
				}, 1)
				this.$nextTick(() => {
					if(window.getSelection) { //ie11 10 9 ff safari
						obj.focus(); //解决ff不获取焦点无法定位问题
						let range = window.getSelection(); //创建range
						range.selectAllChildren(obj); //range 选择obj下所有子内容
						range.collapseToEnd(); //光标移至最后
					} else if(document.selection) { //ie10 9 8 7 6 5
						let range = document.selection.createRange(); //创建选择对象
						range.moveToElementText(obj); //range定位到obj
						range.collapse(false); //光标移至最后
						range.select();
					}
				})
				this.isChange = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	.sxc-text {
		width: 100%;
		min-height: 100%;
		padding: 5px;
		border: none;
		outline: none;
		box-shadow: none;
	}
</style>